/*
 * @Date: 2024-03-27 18:26:44
 * @LastEditTime: 2024-03-27 18:47:18
 * @Description: 获取token
 */
import * as superagent from 'superagent';
import { Token } from '@models/Token';
import { BAIDU_KEY } from '../config';
import { curTime } from '@/common/utils';

/**
 * 服务端获取token
 * @param ID 
 * @param SECRET 
 * @returns 
 */
const ajaxToken = (ID: string, SECRET: string): Promise<{
    access_token: string,
    expires_in: number
}> => {
    return new Promise((resolve) => {
        const url = `https://aip.baidubce.com/oauth/2.0/token?grant_type=client_credentials&client_id=${ID}&client_secret=${SECRET}`;
        const agent = superagent.post(url);
        agent.end((err, res) => {
            if (err) {
                throw err;
            }
            console.log(curTime(), "从百度云获取token");
            resolve(res.body);
        })
    });
}

/**
 * 获取token
 * @param type 
 * @returns 
 */
export const getToken = async (type: 'SOUND' | 'TEXT') => {
    const keys = BAIDU_KEY[type];
    const tokenDbItem = await Token.findOne({ type }).lean().exec();
    if (tokenDbItem) {
        // 判断缓存是否过去
        if (tokenDbItem.value && tokenDbItem.createTime + tokenDbItem.expires_in * 1000 > new Date().getTime() - 1000 * 60 * 10) {
            console.log(curTime(), "从缓存获取token=", tokenDbItem.value);
            return tokenDbItem.value;
        } else {
            console.log(curTime(), '缓存已过期');
        }
    }
    // 从服务器获取
    const newToken = await ajaxToken(keys.ID, keys.SECRET);
    // 保存到数据库
    await Token.deleteOne({ type }).lean().exec();
    Token.create({
        value: newToken.access_token,
        createTime: new Date().getTime(),
        expires_in: newToken.expires_in,
        type
    });
    return newToken.access_token;
}